package com.hmall.item;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.item.config.MqConfiguration;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.ItemDoc;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;

import java.util.List;

@SpringBootTest
public class test {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    void testInsert() throws Exception {
        int i = 0;
        while (true) {
            BulkRequest bulkRequest = new BulkRequest("item");
            Page<Item> itemPage = new Page<>(i, 100);
            i++;
            itemMapper.selectPage(itemPage, null);
            List<Item> itemList = itemPage.getRecords();
            if (CollectionUtils.isEmpty(itemList)) {
                break;
            }
            itemList.forEach(item -> {
                ItemDoc itemDoc = new ItemDoc(item);
                IndexRequest indexRequest = new IndexRequest("item").id(item.getId().toString());
                indexRequest.source(JSON.toJSONString(itemDoc), XContentType.JSON);
                bulkRequest.add(indexRequest);
            });
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            Thread.sleep(1000);
        }
    }

    @Test
    void name() {
        rabbitTemplate.convertAndSend(MqConfiguration.ITEM_TOPIC,"erf");
    }
}
